import React, { useCallback, useEffect, useState } from 'react'

export default function UseCallbackParent() {
  const [count, setCount] = useState(0)
  const [curTime, setCurTime] = useState('')

  const useTime = () => {
    useEffect(() => {
      const intervalId = setInterval(() => {
        const time = new Date()
        setCurTime(time.toLocaleString())
      }, 1000)

      return () => {
        clearInterval(intervalId)
      }
    }, [])

    return curTime
  }

  const time = useTime()

  /**
   * useCallback 为 useMemo 的语法糖
   * const onCountChange = useMemo(() => {
   *   return () => {
   *     setCount((count) => count + 100);
   *   };
   * }, []);
   */
  const onCountChange = useCallback(() => {
    setCount((count) => count + 100)
  }, [])

  // console.log('re-render-father')

  return (
    <div>
      <div>{time}</div>
      <div>{count}</div>
      <UseCallbackChild onCountChange={onCountChange} />
    </div>
  )
}

const UseCallbackChild = React.memo(function UseCallbackChild(props: any) {
  const { onCountChange } = props
  console.log('re-render-child')

  return (
    <>
      <div
        onClick={() => {
          onCountChange()
        }}
      >
        加100
      </div>
    </>
  )
})
